package com.huicoo.forestmanager.ui;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseApplication;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.ui.login.LoginActivity;
import com.huicoo.forestmanager.ui.login.contract.LoginContract;
import com.huicoo.forestmanager.ui.login.presenter.LoginPresenter;
import com.huicoo.forestmanager.ui.main.MainActivity;
import com.huicoo.forestmanager.util.CommonUtil;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.PermissionUtil;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.LoadingDialog;

public class SplashActivity extends AppCompatActivity implements LoginContract.View, Handler.Callback {
    private LoginPresenter presenter;
    private LoadingDialog loadingDialog;
    private WeakHandler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }

        LogUtils.v("---生命周期---：" + this.getClass().getName() + " create");
        // 设置activity无标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        // 设置activity横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        setContentView(R.layout.activity_splash);
        // 屏幕适配
        DisplayUtil.setCustomDensity(this, BaseApplication.getMyApplication());

        initView();
    }

    private void initView() {
        handler = new WeakHandler(this);

        // 初始创建设备唯一识别码，并保存
        if (TextUtils.isEmpty(SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.UNIQUE_ID))) {
            SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.UNIQUE_ID, CommonUtil.getUniqueId(getApplicationContext()));
        }
        LogUtils.v("gogogo app id = " + SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.UNIQUE_ID));

        if (Build.VERSION.SDK_INT >= 23 && PermissionUtil.checkPermission(this, PermissionUtil.SPLASH_PERMISSIONS).length > 0) {
            PermissionUtil.checkAndRequestPermissions(this, PermissionUtil.SPLASH_PERMISSIONS);
        } else {
            intentToMainActivity();
        }
    }

    @Override
    protected void onDestroy() {
        LogUtils.v("---生命周期---：" + this.getClass().getName() + " destroy");
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
            presenter = null;
        }
        if (loadingDialog != null) {
            loadingDialog = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionGrant = false;
        if (requestCode == PermissionUtil.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult == -1) {
                    hasPermissionGrant = true;
                    break;
                }
            }
            if (hasPermissionGrant) {
                ToastUtils.show("允许应用获取权限方可继续使用");
                finish();
            } else {
                intentToMainActivity();
            }
        }
    }

    private void intentToMainActivity() {
        String lastAccount = CustomUtils.getUserAccount();
        String lastPassword = CustomUtils.getUserPassword();
        if (!TextUtils.isEmpty(lastAccount) && !TextUtils.isEmpty(lastPassword)) {
            if (presenter == null) {
                presenter = new LoginPresenter(this);
            }
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog(this);
            }
            loadingDialog.show();
            if (handler != null){
                Message loginMsg = new Message();
                loginMsg.what = 110;
                handler.sendMessageDelayed(loginMsg, 250);
            }
        } else {
            if (handler != null) {
                Message loginMsg = new Message();
                loginMsg.what = 111;
                handler.sendMessageDelayed(loginMsg, 500);
            }
        }
    }

    @Override
    public void loginSuccess() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginFail(String msg) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show(TextUtils.isEmpty(msg) ? "请重新登录" : msg + "，请重新登录");
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 110:
                String lastAccount = CustomUtils.getUserAccount();
                String lastPassword = CustomUtils.getUserPassword();
                presenter.login(lastAccount, lastPassword);
                break;
            case 111:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
        return false;
    }
}
